/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.com.losalpes.marketplace.pirfb.entities.test;

/**
 *
 * @author leon
 */
import co.com.losalpes.marketplace.pirfb.entities.Intencion;
import co.com.losalpes.marketplace.pirfb.entities.persistence.Persistence;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

public class InicializarIntencion {

    //5
    //5
    public static final String[] categorias = {"Ropa", "Alimentos", "Celulares", "Computadores", "Calzado"};
    public static final String[] ropa = {"Camiseta", "Pantalon", "Medias", "Chaqueta", "Buzo"};
    public static final String[] alimentos = {"Pollo", "Leche", "Huevos", "Cerdo", "Galletas"};
    public static final String[] celulares = {"Nokia", "Xpiria 11", "Samsung Galaxy 1", "HTC One", "Motorla Razr"};
    public static final String[] computadores = {"Lenovo ", "Toshiba", "Compaq", "HP", "Sony"};
    public static final String[] calzado = {"Tenis", "Zapatos", "Chancletas", "Zapatillas", "Botas"};
    public static final String[][] productos = {ropa, alimentos, celulares, computadores, calzado};
    private static Random ranGen = new Random();

    /**
     * Inserta xx elementos en tabla cotizacion
     *
     * @param args
     */
    public static void main(String args[]) {
        Intencion intencion;
        Persistence persistence = new Persistence();
        //crear intenciones de venta y de compra
        for (int i = 0; i < 50; i++) {
            intencion = incializarIntencion();
            persistence.persist(intencion);
            Intencion elMatch = match(intencion);
            if (elMatch != null) {
                java.lang.System.out.println("Match: " + intencion.getNumero() + " - " + elMatch.getNumero());
            }
        }



    }

    private static Intencion match(Intencion intencion) {
        EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("PI_RFB_jpaPU");
        EntityManager em = emf.createEntityManager();
        try {
            Persistence persistence = new Persistence();
            String sql = "SELECT "
                    + " i2.id "
                    + "FROM "
                    + " intencion i1 "
                    + "  INNER JOIN intencion i2 "
                    + "  ON i2.tipo != i1.tipo AND "
                    + "   i2.estado = 'ABIERTA' AND "
                    + "   i2.categoria = i1.categoria AND "
                    + "   i2.producto = i1.producto AND "
                    + "   i2.cantidad > i1.cantidad * .7 AND "
                    + "   i2.cantidad < i1.cantidad * 1.3 AND "
                    + "   i2.valor > i1.valor * .7 AND "
                    + "   i2.valor < i1.valor * 1.3 "
                    + "WHERE "
                    + " i1.id = ?1 "
                    + "ORDER BY "
                    + " i2.id ASC, i2.fecha_max_espera DESC, i2.valor "
                    + (String) ((intencion.getTipo().equals(Intencion.T_COMPRA)) ? "DESC" : "ASC")
                    + " LIMIT 0,1;";
            Query query = em.createNativeQuery(sql);
            query.setParameter(1, intencion.getId());
            List ret = query.getResultList();
            if (!ret.isEmpty()) {
                Integer idMatch = (Integer) ret.get(0);
                query = persistence.createQuery("SELECT inten FROM Intencion inten WHERE inten.id = :id");
                query.setParameter("id", idMatch);
                return (Intencion) query.getSingleResult();
            } else {
                return null;
            }
        } finally {
            emf.close();
        }
    }

    private static Intencion incializarIntencion() {
        Intencion c = new Intencion();
        String seq = "INT" + System.currentTimeMillis();
        c.setNumero(seq);
        c.setNit(ranGen.nextInt(20) + "");
        c.setUser(c.getNit());
        c.setEstado(Intencion.E_ABIERTA);
        c.setTipo(ranGen.nextBoolean() ? Intencion.T_COMPRA : Intencion.T_VENTA);
        int cat = ranGen.nextInt(4);
        c.setCategoria(categorias[cat]);
        c.setProducto(productos[cat][ranGen.nextInt(4)]);
        c.setCantidad(ranGen.nextInt(50));
        int month = ranGen.nextInt(2) + 10;
        int day = ranGen.nextInt(30);
        c.setFecha_entrega(new Date(113, month, day));
        c.setFecha_max_espera(new Date(113, month + ranGen.nextInt(1), day + ranGen.nextInt(15) + 15));
        c.setValor(ranGen.nextInt(20) * 5000);
        return c;
    }
}
